/// HTML 内容生成工具类
class HtmlContentGenerator {
  /// 判断字符串是否包含 HTML 标签
  static bool containsHtmlTags(String content) {
    final htmlPattern = RegExp(r'<[^>]+>');
    return htmlPattern.hasMatch(content);
  }

  /// 判断是否为视频文件
  static bool isVideoFile(String url) {
    final videoExtensions = ['mp4', 'mov', 'avi', 'mkv', 'flv', 'm4v'];
    final uri = Uri.tryParse(url);
    if (uri == null) return false;
    final path = uri.path.toLowerCase();
    final extension = path.split('.').last;
    return videoExtensions.contains(extension);
  }

  /// 判断是否为图片文件
  static bool isImageFile(String url) {
    final imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
    final uri = Uri.tryParse(url);
    if (uri == null) return false;
    final path = uri.path.toLowerCase();
    final extension = path.split('.').last;
    return imageExtensions.contains(extension);
  }

  /// 处理 HTML 内容
  /// 如果包含 HTML 标签，直接使用；否则将纯文本转换为 HTML 格式
  static String _processHtmlContent(String content) {
    // 判断是否包含 HTML 标签
    if (containsHtmlTags(content)) {
      // 已包含 HTML 标签，直接返回
      return content;
    } else {
      // 纯文本，需要进行 HTML 转义并处理换行
      final escaped = _escapeHtml(content);
      // 将换行符转换为 <br> 标签
      return escaped.replaceAll('\n', '<br>');
    }
  }

  /// 生成富文本 HTML（带放大字体）
  static String withZoomedFontSize({required String content, String? title}) {
    final css = '''
      <style>
        body {
          margin: 0;
          padding: 0 16px; 
          font-size: 16px; 
          word-wrap: break-word;
        }
        img {
          max-width: 95%;
          height: auto;
          display: block;
        }
        table {
          width: 100% !important;
        }
        h1.injected-title {
          font-size: 18px;  
          font-weight: bold;
          margin: 0 0 12px 0;
        }
      </style>
    ''';

    final titleHTML = (title != null && title.isNotEmpty)
        ? '<h1 class="injected-title">${_escapeHtml(title)}</h1>'
        : '';

    // 处理 content，如果是 HTML 直接使用，如果是纯文本则转义并处理换行
    final processedContent = _processHtmlContent(content);

    final htmlTemplate =
        '''
      <!DOCTYPE html>
      <html>
      <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        $css
      </head>
      <body>
        $titleHTML
        $processedContent
      </body>
      </html>
    ''';

    return htmlTemplate;
  }

  /// 生成图片轮播 HTML (适配 iOS WebView 手势)
  /// 生成图片轮播 HTML (适配 iOS WebView 手势 + 边缘 0 间距 + 指示器右上角)
  static String toCarouselHTML({
    required List<String> imageUrls,
    required String title,
    required String content,
    int height = 300,
  }) {
    // 1. 处理图片 URL
    final size = (height * 1.3).round();
    final processedUrls = imageUrls.where((url) => url.isNotEmpty).map((url) {
      final trimmed = url.trim();
      if (!trimmed.contains('?')) {
        return '$trimmed?imageView2/1/w/$size/h/$size/format/webp/interlace/1/ignore-error/1';
      }
      return trimmed;
    }).toList();

    // 2. 生成 JS 数组
    final imagesJSArray = processedUrls
        .map((url) => '"${_escapeJs(url)}"')
        .join(', ');

    // 3. 构建 HTML
    final html =
        '''
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
        <style>
          /* 全局重置 */
          * { box-sizing: border-box; margin: 0; padding: 0; }
          
          body {
            font-family: -apple-system, sans-serif;
            font-size: 16px;
            /* body 去除内边距，实现图片左右顶头、上顶头 */
            padding: 0; 
            margin: 0;
            overflow-x: hidden; 
            background-color: #fff;
          }

          .carousel {
            position: relative;
            overflow: hidden;
            width: 100%;
            height: ${height}px;
            /* 去除圆角，直角贴边 */
            border-radius: 0; 
            
            /* --- WebView 关键兼容样式 --- */
            -webkit-user-select: none;
            -webkit-touch-callout: none;
            user-select: none;
            touch-action: pan-y;
          }

          .slides {
            display: flex;
            width: 100%;
            height: 100%;
            transition: transform 0.3s ease-in-out;
            will-change: transform;
          }

          .slide {
            min-width: 100%;
            height: 100%;
            background-size: cover;
            background-position: center;
          }

          .indicator {
            position: absolute;
            /* 修改此处：改为右上角 */
            top: 12px;
            right: 12px;
            
            background: rgba(0, 0, 0, 0.5);
            color: white;
            font-size: 12px;
            padding: 4px 10px;
            border-radius: 12px;
            pointer-events: none; /* 让点击穿透 */
            z-index: 10;
          }

          /* 标题样式：手动补充左右留白 */
          .title {
            font-size: 1.25rem;
            font-weight: 600;
            text-align: left;
            margin-top: 20px;
            padding: 0 16px; 
            line-height: 1.4;
          }

          /* 内容样式：手动补充留白 */
          .content {
            padding: 16px; 
            font-size: 1.05rem;
            line-height: 1.6;
            color: #333;
            white-space: pre-wrap;
          }
        </style>
      </head>
      <body>
        <div class="carousel" id="carousel-box">
          <div class="slides" id="slides"></div>
          <!-- 指示器 -->
          <div class="indicator" id="indicator">1/${processedUrls.length}</div>
        </div>
        
        <div class="title">${_escapeHtml(title)}</div>
        <div class="content">${_processHtmlContent(content)}</div>
        
        <script>
          const imageUrls = [$imagesJSArray];
          const slidesEl = document.getElementById('slides');
          const indicatorEl = document.getElementById('indicator');
          const carouselEl = document.getElementById('carousel-box');

          // 初始化 DOM
          imageUrls.forEach((url) => {
            const slide = document.createElement('div');
            slide.className = 'slide';
            slide.style.backgroundImage = \`url(\${url})\`;
            slidesEl.appendChild(slide);
          });

          let currentIndex = 0;
          function showSlide(index) {
            if (index < 0 || index >= imageUrls.length) return;
            currentIndex = index;
            slidesEl.style.transform = \`translateX(-\${index * 100}%)\`;
            indicatorEl.textContent = \`\${index + 1}/\${imageUrls.length}\`;
          }

          // --- 适配 iOS WebView 的手势逻辑 ---
          let startX = 0;
          let startY = 0;
          let isHorizontal = false;
          let isLocked = false;

          // 1. Touch Start
          carouselEl.addEventListener('touchstart', function (e) {
            startX = e.touches[0].clientX;
            startY = e.touches[0].clientY;
            isHorizontal = false;
            isLocked = false;
          }, { passive: false });

          // 2. Touch Move (锁定方向 + 阻止滚动)
          carouselEl.addEventListener('touchmove', function (e) {
            const moveX = e.touches[0].clientX;
            const moveY = e.touches[0].clientY;
            const diffX = Math.abs(moveX - startX);
            const diffY = Math.abs(moveY - startY);

            if (!isLocked) {
              if (diffX > 5 || diffY > 5) {
                isLocked = true;
                if (diffX > diffY) {
                  isHorizontal = true;
                }
              }
            }

            if (isLocked && isHorizontal) {
              if (e.cancelable) {
                e.preventDefault();
                e.stopPropagation();
              }
            }
          }, { passive: false });

          // 3. Touch End
          carouselEl.addEventListener('touchend', function (e) {
            if (!isHorizontal) return;

            const endX = e.changedTouches[0].clientX;
            const delta = endX - startX;
            
            if (Math.abs(delta) < 40) return; 

            if (delta > 0) {
              showSlide(currentIndex - 1);
            } else {
              showSlide(currentIndex + 1);
            }
          });

          showSlide(0);
        </script>
      </body>
      </html>
    ''';

    return html;
  }

  /// 生成视频播放 HTML (自定义 UI：右下角全屏/小窗，中间播放，无遮罩)
  /// 生成视频播放 HTML (无闪烁版：CSS背景图 + preload=none + 极简UI)
  static String toVideoHTML({
    required String videoUrl,
    required String coverImgUrl,
    required String title,
    required String content,
    int height = 250,
  }) {
    final trimmedUrl = videoUrl.trim();
    final trimmedCover = coverImgUrl.trim();

    return '''
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
        <style>
          /* 1. 全局重置 */
          * { box-sizing: border-box; margin: 0; padding: 0; }
          
          body {
            font-family: -apple-system, sans-serif;
            font-size: 16px;
            padding: 0; 
            margin: 0;
            background-color: #fff;
            overflow-x: hidden;
            -webkit-user-select: none;
            user-select: none;
            /* 防止点击高亮 */
            -webkit-tap-highlight-color: transparent;
          }

          /* 视频容器 */
          .video-container {
            position: relative;
            width: 100%;
            height: ${height}px;
            border-radius: 0; 
            overflow: hidden;
            
            /* --- 核心防闪烁优化 --- */
            /* 1. 设置背景色为白色(与body一致)或灰色，避免黑块闪烁 */
            background-color: #f0f0f0; 
            
            /* 2. 直接将封面设为容器背景，CSS渲染比video标签快，消除加载白屏/黑屏 */
            background-image: url('${_escapeJs(trimmedCover)}');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
          }

          /* 视频标签 */
          video {
            width: 100%;
            height: 100%;
            object-fit: cover; 
            display: block;
            
            /* 确保视频未播放时不会遮挡背景图 */
            position: relative;
            z-index: 1;
          }
          
          /* 隐藏原生控件 */
          video::-webkit-media-controls { display: none !important; }
          video::-webkit-media-controls-enclosure { display: none !important; }

          /* --- 中间播放按钮 --- */
          .center-play-btn {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 64px;
            height: 64px;
            background: rgba(0, 0, 0, 0.4);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            z-index: 10; /* 保证在 video 之上 */
            transition: opacity 0.2s, transform 0.1s;
          }
          
          .center-play-btn:active {
            transform: translate(-50%, -50%) scale(0.95);
            background: rgba(0, 0, 0, 0.6);
          }
          
          .play-icon {
            width: 0; 
            height: 0; 
            border-top: 12px solid transparent;
            border-bottom: 12px solid transparent;
            border-left: 20px solid #fff;
            margin-left: 6px; 
          }

          .hidden {
            opacity: 0;
            pointer-events: none;
          }

          /* 文字区域 */
          .title {
            font-size: 1.25rem;
            font-weight: 600;
            margin-top: 16px;
            margin-bottom: 12px;
            padding: 0 16px; 
            line-height: 1.4;
          }

          .content {
            padding: 0 16px 20px 16px; 
            font-size: 1rem;
            line-height: 1.6;
            color: #333;
            white-space: pre-wrap;
          }
        </style>
      </head>
      <body>
        <div class="video-container">
          <!-- 
             防闪烁关键设置：
             1. poster: 依然保留作为双重保险
             2. preload="none": 核心！禁止视频预加载。
                如果不设为none，iOS会尝试加载视频元数据，
                导致瞬间黑屏或重新渲染布局，引起闪烁。
          -->
          <video 
            id="mainVideo"
            src="${_escapeHtml(trimmedUrl)}" 
            poster="${_escapeHtml(trimmedCover)}" 
            preload="none" 
            playsinline 
            webkit-playsinline 
            x5-playsinline>
          </video>

          <div class="center-play-btn" id="centerBtn">
            <div class="play-icon"></div>
          </div>
        </div>

        <div class="title">${_escapeHtml(title)}</div>
        <div class="content">${_processHtmlContent(content)}</div>

        <script>
          document.addEventListener('DOMContentLoaded', function() {
            var video = document.getElementById('mainVideo');
            var centerBtn = document.getElementById('centerBtn');
            
            function playVideo() {
              video.play();
              centerBtn.classList.add('hidden');
            }
            
            function pauseVideo() {
              video.pause();
              centerBtn.classList.remove('hidden');
            }

            // 点击按钮
            centerBtn.addEventListener('click', function(e) {
              e.stopPropagation();
              if (video.paused) {
                playVideo();
              } else {
                pauseVideo();
              }
            });

            // 点击视频区域
            video.addEventListener('click', function() {
              if (video.paused) {
                playVideo();
              } else {
                pauseVideo();
              }
            });

            // 状态监听
            video.addEventListener('play', function() {
              centerBtn.classList.add('hidden');
            });
            
            video.addEventListener('pause', function() {
              centerBtn.classList.remove('hidden');
            });
            
            video.addEventListener('ended', function() {
              centerBtn.classList.remove('hidden');
              // 播放结束后，重新显示封面 (iOS有时会停在最后一帧，有时黑屏，视系统版本而定)
              // 这里选择保持不动，或者你可以 reload video
            });
          });
        </script>
      </body>
      </html>
    ''';
  }

  /// 转义 HTML 特殊字符
  static String _escapeHtml(String text) {
    return text
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;')
        .replaceAll("'", '&#x27;');
  }

  /// 转义 JavaScript 字符串
  static String _escapeJs(String text) {
    return text
        .replaceAll('\\', '\\\\')
        .replaceAll('"', '\\"')
        .replaceAll('\n', '\\n')
        .replaceAll('\r', '\\r');
  }
}
